package cn.edu.scau.dormitory_management_system.controller;


import cn.edu.scau.dormitory_management_system.entity.PermissionEntity;
import cn.edu.scau.dormitory_management_system.entity.RoleEntity;
import cn.edu.scau.dormitory_management_system.entity.RolePermissionEntity;
import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.entity.dto.RoleDto;
import cn.edu.scau.dormitory_management_system.module.user.service.UserService;
import cn.edu.scau.dormitory_management_system.service.PermissionService;
import cn.edu.scau.dormitory_management_system.service.RolePermissionService;
import cn.edu.scau.dormitory_management_system.service.RoleService;
import cn.edu.scau.dormitory_management_system.service.UserRoleService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 
 *
 * @author whj
 * @date 2021-08-02 14:35:10
 */
@RestController
@RequestMapping("/admin/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermission;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private PermissionService permissionService;
    /**
     *
     * @param roleName 角色名
     * @param remark    备注
     * @param menuIdList 权限
     * @return
     */
    @PostMapping("/insert")
        public Object insertRole(@RequestParam("roleName") String roleName,
                             @RequestParam("remark") String remark,
                             @RequestParam("menuIdList") String menuIdList, HttpServletRequest request){
        UserEntity user = (UserEntity)request.getAttribute("admin");
        int id = roleService.insertRole(roleName, remark, user);
        JSONObject object = new JSONObject();
        if(id > 0){
            int insert = rolePermission.insert(id, menuIdList, user);
            if(insert > 0) {
                object.put("code", 200);
                object.put("msg", "插入成功");
                return object;
            }
        }
        object.put("code", 0);
        object.put("msg", "插入失败");
        return object;
    }
    /**
     * @param roleId 角色Id
     * @param roleName 角色名
     * @param remark    备注
     * @return
     */
    @PostMapping("/update")
    public Object updateRole(@RequestParam("roleId") int roleId,
                             @RequestParam("roleName") String roleName,
                             @RequestParam("remark") String remark,
                             @RequestParam("menuIdList") String menuIdList, HttpServletRequest request){
        UserEntity user = (UserEntity)request.getAttribute("admin");
        int update = roleService.updateRole(roleId,roleName, remark, user);
        JSONObject object = new JSONObject();
        if(update > 0){
            int insert = rolePermission.update(roleId, menuIdList, user);
            if(insert > 0) {
                object.put("code", 200);
                object.put("msg", "修改成功");
                return object;
            }
        }
        object.put("code", 0);
        object.put("msg", "修改失败");
        return object;
    }
    /**
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    public Object deleteRole(@RequestParam("roleIds") String roleIds){
        String[] split = roleIds.split(",");
        for (int i = 0; i < split.length; i++) {
            Integer id = Integer.valueOf(split[i]);
            roleService.removeById(id);
            HashMap<String, Object> map = new HashMap<>();
            map.put("role_id",id);
            rolePermission.removeByMap(map);
            userRoleService.removeByMap(map);
        }
        JSONObject object = new JSONObject();
        object.put("code", 200);
        object.put("msg", "删除成功");
        return object;
    }

    /**
     *
     * @return
     */
    @GetMapping("/info/{roleId}")
    public Object selectRole(@PathVariable("roleId") int roleId){
        RoleEntity role = roleService.getById(roleId);
        QueryWrapper<RolePermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<RolePermissionEntity> list = rolePermission.list(queryWrapper);
        ArrayList<Integer> integers = new ArrayList<>();
        ArrayList<PermissionEntity> permissionEntities = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            permissionEntities.add(permissionService.getById(list.get(i).getPermissionId()));
        }
        int len = 0;
        for (int i = 0; i < permissionEntities.size(); i++) {
            integers.add(permissionEntities.get(i).getMenuId());
            if (permissionEntities.get(i).getType() != 2) {
                for (int j = 0; j < permissionEntities.size(); j++) {
                    if (permissionEntities.get(j).getParentId() == permissionEntities.get(i).getMenuId()){
                        integers.remove(len);
                        len--;
                        break;
                    }
                }
            }
            len++;
        }
        int[] menuIdList = new int[integers.size()];
        for (int i = 0; i < menuIdList.length; i++) {
            menuIdList[i] = integers.get(i);
        }
        JSONObject object = new JSONObject();
        object.put("role", role);
        object.put("menuIdList", menuIdList);
        object.put("code", 200);
        object.put("msg", "查询成功");
        return object;
    }

    @GetMapping("/listAll")
    public Object listAll(@RequestParam("page")int page,
                       @RequestParam("limit")int limit,
                       @RequestParam("rolename")String rolename){
        Page<RoleEntity> roleEntityPage = new Page<>(page,limit);
        QueryWrapper<RoleEntity> roleEntityQueryWrapper = new QueryWrapper<>();
        roleEntityQueryWrapper.like("role_name",rolename);
        Page<RoleEntity> page1 = roleService.page(roleEntityPage, roleEntityQueryWrapper);
        JSONObject object = new JSONObject();
        object.put("page", page1);
        object.put("code", 200);
        object.put("msg", "查询成功");
        return object;
    }
    @GetMapping("/list")
    public Object list(){
        List<RoleEntity> list = roleService.list();
        JSONObject object = new JSONObject();
        object.put("list", list);
        object.put("code", 200);
        object.put("msg", "查询成功");
        return object;
    }
}
